﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Text;
using KFGame;

public class ICCardHander : MonoBehaviour
{
    // Start is called before the first frame update
    public KFSeralPort seralPorC;

    public delegate void CarDatas(byte[] datas);
    public CarDatas onCarDatas;

    void Start()
    {
        ICardSetting setting = LoadConfigDatas();

        seralPorC = KFSeralPort.GetSeralPort(setting.comName);
        seralPorC.baudRate = setting.baudRate;
        seralPorC.open();

    }

    public static ICardSetting LoadConfigDatas(string path = null)
    {
        if (path == null)
            path = System.IO.Path.Combine(Application.streamingAssetsPath, "ICardHander.json");

        if (!File.Exists(path))
            return new ICardSetting();

        StreamReader sr = new StreamReader(path);
        if (sr == null)
            return new ICardSetting();

        string json = sr.ReadToEnd();
        sr.Close();

        if (json.Length > 0)
            return JsonUtility.FromJson<ICardSetting>(json);
        return new ICardSetting();
    }
    // Update is called once per frame
    void Update()
    {
        byte[] datas = new byte[1];
        if (getDatas(ref datas))
            if (checkDatas(datas))
                if (onCarDatas != null)
                    onCarDatas(datas);


    }



    //读取数据
    public bool getDatas(ref byte[] datas)
    {
        byte ldata = 0x00;
        if (seralPorC.checkData(ref ldata, 1))
        {
            if (ldata > seralPorC.canReadCont())
                return false;
            byte[] data = new byte[ldata];
            if (seralPorC.read(ref data))
            {
                datas = data;
                return true;
            }

        }
        return false;
    }

    //验证数据
    public bool checkDatas(byte[] datas)
    {
        byte checksum = 0x00;
        //异或
        for (int i = 0; i < (datas.Length - 1); i++)
            checksum ^= datas[i];
        //取反
        checksum = (byte)~checksum;
        return (checksum == datas[datas.Length - 1]);

    }
}
